/*
 * $Id: JsonEngineConnector.java 136 2009-07-16 07:53:43Z donbeave $
 */

package labour.concept.engine.client.data.json;

import java.util.List;
import java.util.Map;

import labour.concept.client.data.ObjectModel;
import labour.concept.client.data.ObjectsLoadResult;
import labour.concept.client.data.json.JsonConceptConnector;
import labour.concept.client.data.json.JsonReadersContainer;
import labour.concept.engine.client.EngineConnector;
import labour.concept.engine.client.data.EngineObjectModel;
import labour.concept.engine.client.data.SiteModel;
import labour.concept.engine.client.data.SiteModelType;

import com.google.gwt.user.client.rpc.AsyncCallback;

public class JsonEngineConnector extends JsonConceptConnector implements EngineConnector {

  private JsonSitesReader<SiteModel> sitesReader;

  public JsonEngineConnector(String url) {
    super(url);
  }

  public JsonSitesReader<SiteModel> getSitesReader() {
    if (sitesReader == null) {
      sitesReader = createSitesReader();
    }
    return sitesReader;
  }

  public void loadSites(final AsyncCallback<List<SiteModel>> callback) {
    loadBasicData(new AsyncCallback<Map<String, ?>>() {
      public void onFailure(Throwable caught) {
        callback.onFailure(caught);
      }

      @SuppressWarnings("unchecked")
      public void onSuccess(Map<String, ?> result) {
        callback.onSuccess((List<SiteModel>) result.get("sites"));
      }
    });
  }

  public void loadRootObjects(String siteId, AsyncCallback<ObjectsLoadResult<EngineObjectModel>> callback) {
    // TODO передать серверу id сайт загружаемых объектов
    loadObjects(null, callback);
  }

  public void loadObjectChildren(ObjectModel parent, AsyncCallback<ObjectsLoadResult<EngineObjectModel>> callback) {
    loadObjects(parent, callback);
  }

  @Override
  protected JsonReadersContainer createBasicReader() {
    JsonReadersContainer reader = super.createBasicReader();
    reader.registerReader("sites", getSitesReader());
    return reader;
  }

  protected JsonSitesReader<SiteModel> createSitesReader() {
    return new JsonSitesReader<SiteModel>(new SiteModelType());
  }

}
